package com.ldy.interceptor;

import com.ldy.annotation.AccessControl;
import com.ldy.util.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 描述：访问控制嵌入式拦截器<br>
 * 版权：Copyright (c) 2011 ~ 2017<br>
 * 公司：北京活力天汇<br>
 * 作者：刘德咏<br>
 * 版本：1.0<br>
 * 创建日期：2017/9/27<br>
 */
public class AccessControlInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(AccessControlInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Class<?> clazz = handler.getClass();
//        if (clazz.isAnnotationPresent(AccessControl.class)) {
            for (Method method : clazz.getMethods()) {
                if (method.isAnnotationPresent(AccessControl.class)) {
                    AccessControl accessControl = clazz.getAnnotation(AccessControl.class);
                    String project = accessControl.value();
                    String ip = IPUtils.getIp(request);
                   logger.debug("project:{}, ip:{}", project, ip);
                    return true;
                }
            }
//        }
        return false;
    }
}
